﻿//the function is defined to show or hide error information of page
function ShowHideValidationSummary(isShowed) {
    if (isShowed == true) {
        $("#ValidationSummary").show();
    }
    else {
        $("#ValidationSummary").hide();
    }
}

/*======================================================================  
Description : Get , Set & Delete a cookie at client site
======================================================================== */
function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name, "", -1);
}
/*=========================================================================
Description : Blink message
=========================================================================*/
function Blink(selector) {
    $(selector).fadeOut('slow', function () {
        $(this).fadeIn('slow', function () {
            Blink(this);
        });
    });
}

/*  
Description : Clear form
*/
function ClearFormElements(ele) {

    $(ele).find(':input').each(function () {
        switch (this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });

}

/*  
Description : Convert to DateTime string to datetime ("MMM dd, yyyy hh:mm tt")
Parameters  : mask { "shortdate", "longdate", "time" }
*/
function FormatDateTimeString(mask, value) {
    if (value == "")
        return "";
    if (mask == "shortdate") {
        //"01-Dec-2012" => "Dec 01, 2012"
        var array = value.split('-');
        return new Date(String.format('{0} {1}, {2}', array[0], array[1], array[2]));
    } else if (mask == "longdate") {
        //"01-Dec-2012 11:30 pm" => "Dec 01, 2012 11:30 pm"
        var array = value.split('-');
        var times = array[2].split(' ');
        return new Date(String.format('{0} {1}, {2} {3} {4}', array[0], array[1], times[0], times[1], times[2]));
    } else if (mask == "time") {
        //"11:30 pm" => "Dec 01, 2012 11:30 pm"
        return new Date(String.format('Jan 01, 1900 {0}', value));
    }
    return "";
}

/*  
Description : Diff Date between 2 days
*/
function DiffDate(fromDate, toDate) {
    var diffMs = (fromDate - toDate);
    var diffDays = Math.round(diffMs / 86400000); // days
    var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
    var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
    var totalMins = Math.round(diffMs / 60000); //convert millisecond to minutes
    var totalHours = Math.round((diffMs / 60000) / 60); //convert millisecond to hours
    var oDiff = new Object();
    oDiff.milliseconds = diffMs;
    oDiff.days = diffDays;
    oDiff.hours = diffHrs;
    oDiff.minutes = diffMins;
    oDiff.TotalMinutes = totalMins;
    oDiff.TotalHours = totalHours;
    return oDiff;
}

/*  
Description : Convert datetime ajax /Date(1353496818167)/ to standard datetime
Example     : ConvertDateTimeAjax("/Date(1353496818167)/", true) -> Result : "18-Oct-12 11:15 PM"
*/
function ConvertDateTimeAjax(dateString, isGetDateTime, onlyTime) {
    if (dateString == "" || dateString == null)
        return "";
    if (dateString.indexOf("-") > -1)
        return "";
    if (dateString.indexOf("-") > -1)
        return "";
    if (isGetDateTime) {
        if ((typeof onlyTime != 'undefined') && (onlyTime == true)) {
            return new Date(parseInt(dateString.substr(6))).format("shortTime");
        } else {
            return new Date(parseInt(dateString.substr(6))).format("shortDateTime");
        }
    }
    return new Date(parseInt(dateString.substr(6))).format("shortDate");
}

/*  
Description : the function is defined to format string by more parameters.
EX          : String.format("test{0}-{1}","A1", "B3"); => "testA1-B2"
*/
String.format = function () {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }

    return s;
};
/*  
Description : the function is defined to create tooltip for dropdownlist.
*/
function CreateDropdownTooltip() {
    $("select:not(.ui-pg-selbox)").each(function () {
        var dropdown = $(this);
        dropdown.find('option').each(function () {
            var option = $(this);
            option.attr('title', option.text());
        });
        if (dropdown.attr('multiple') != 'multiple') {
            dropdown.change(function () {
                dropdown.attr('title', dropdown.find('option :selected').text());
            });
        }
    });
}

/*  
Description : set datetime control is read-only
*/

function DisableDateTimePicker(selector, isDisabled) {
    if (selector.indexOf('#') == -1) {
        selector = "#" + selector;
    }
    if (isDisabled) {
        //inst.dpDiv = $('<div style="display: none;"></div>');
        //$(selector).datepicker("option", "beforeShow", function (input, inst) { inst.dpDiv = $('<div style="display: none;"></div>'); });
        //$(selector).datepicker('disable');
        $(selector).css('cssText', 'background-color: #CCC !important;');
        $(selector).datepicker("option", "beforeShow", function (input, inst) { return false; });
    } else {
        //$(selector).datepicker("option", "beforeShow", function (input, inst) {   });
        //$(selector).datepicker('enable');
        $(selector).css('cssText', 'background-color: transparent !important;');
        $(selector).datepicker("option", "beforeShow", function (input, inst) { return true; });
    }
}

/*  
Description : the function is defined to create date picker of jquery.
*/
//Date picker
function CreateDatePickerControl(selector, options) {
    if (selector.indexOf('#') == -1) {
        selector = "#" + selector;
    }

    //defaults
    var defaults = {
        dateFormat: 'dd-M-yy'
		, minDate: new Date(1900, 0, 1, 0, 0, 0, 0) //01-Jan-1900 00:00:00
		, constrainInput: true
		, showOn: 'button'
		, buttonText: 'Date Picker'
		, buttonImageOnly: true
		, buttonImage: imagePathURL + 'iconDatePicker.gif'
		, changeMonth: true
		, changeYear: true
    };

    //merge options
    options = options == 'undefined' ? defaults : options;
    var setting = $.extend(defaults, options);
    $(selector).datepicker(setting);

}

//DateTime picker
function CreateDateTimePickerControl(selector) {
    if (selector.indexOf('#') == -1) {
        selector = "#" + selector;
    }
    $(selector).datetimepicker({
        dateFormat: 'dd-M-yy',
        minDate: new Date(1900, 0, 1, 0, 0, 0, 0), //01-Jan-1900 00:00:00
        constrainInput: true,
        hourGrid: 4,
        minuteGrid: 10,
        timeFormat: 'hh:mm TT',
        showOn: 'button',
        buttonText: 'Date Time Picker',
        buttonImageOnly: true,
        buttonImage: imagePathURL + 'iconDatePicker.gif'
    });
    DisableDateTimePicker(selector, false);
}


//Time picker
function CreateTimePickerControl(selector) {
    if (selector.indexOf('#') == -1) {
        selector = "#" + selector;
    }
    $(selector).timepicker({
        hourGrid: 4,
        minuteGrid: 10,
        timeFormat: 'hh:mm TT',
        constrainInput: true,
        showOn: 'button',
        buttonText: 'Time Picker',
        buttonImageOnly: true,
        buttonImage: imagePathURL + 'time-clock-icon.png'
    });
}
/*  
Description : the function is defined to check string value is integer type
*/
function DiffDateByMonth(month, isAddMonth) {
    var diffDate = new Date();
    if (isAddMonth) {
        diffDate.setMonth(diffDate.getMonth() + month);
    } else {
        diffDate.setMonth(diffDate.getMonth() - month);
    }
    return diffDate;
}


//Check data type of value is number
function IsIntegerNumber(string) {
    var numericExpression = /^[0-9]+$/;

    if (string.match(numericExpression)) {
        return true;
    } else {
        return false;
    }
}

/*  
Description : the function is defined to automatic find text-area controls for register maxlength.
*/
function RegisterTextAreaMaxLength() {
    // ignore these keys   
    var ignore = [8, 9, 13, 33, 34, 35, 36, 37, 38, 39, 40, 46];
    // use keypress instead of keydown as that's the only    
    // place keystrokes could be canceled in Opera   
    var eventName = 'keypress';
    // handle textareas with maxlength attribute   
    $('textarea[maxlength]')
    // this is where the magic happens     
	.live(eventName, function (event) {
	    var self = $(this),
			maxlength = self.attr('maxlength'),
			code = $.data(this, 'keycode');
	    // check if maxlength has a value.       
	    // The value must be greater than 0       
	    if (maxlength && maxlength > 0) {
	        // continue with this keystroke if maxlength
	        // not reached or one of the ignored keys were pressed.         
	        return (self.val().length < maxlength || $.inArray(code, ignore) !== -1);
	    }
	})
    // store keyCode from keydown event for later use     
	.live('keydown', function (event) {
	    $.data(this, 'keycode', event.keyCode || event.which);
	});
};
/*  
Control     : Combobox Customize
Description : the function is defined to convert dropdownlist control to custom combobox control 
Example     : RegisterComboWithOption('#mycombo', {width:100,maxheight: 200}, myFunctionCallback);
*/
function RegisterComboWithOption(selector, opts, fnSelectedCallback) {

    if (opts == null || opts.length == 0) {
        opts = new Object();
        opts.maxheight = 200;
        opts.width = 200;
        opts.isFilter = false;
        opts.autoFill = false;
    }
    //Set default if some properties are not defined
    if (typeof opts.isFilter == 'undefined')
        opts.isFilter = false;
    if (typeof opts.autoFill == 'undefined')
        opts.autoFill = false;

    //Create custom combobox
    $(selector).customCombo({
        suffix: "custom",
        maxheight: opts.maxheight,
        isDropdown: true,
        width: opts.width,
        autoFill: opts.autoFill,
        isFilter: opts.isFilter,
        isDropdown: false,
        emptyText: "",
        changeCallback: (typeof fnSelectedCallback == "function") ? fnSelectedCallback : null,
        triggerSelectedFirstLoad: true
    });

}

/*  
Control     : Combobox Customize
Description : the function is defined to convert dropdownlist control to custom combobox control 
*/
function RegisterCustomCombo(selector, options) {
    var defaults = {
        suffix: "custom",
        isFilter: true,
        isDropdown: false,
        width: 120,
        autoFill: false,
        searchContain: true,
        emptyText: '',
        triggerSelectedFirstLoad: false
    };
    var setting = $.extend(defaults, options);
    $(selector).customCombo(setting);
}

function RegisterCombo(selector, width, fnSelectedCallback) {
    $(selector).customCombo({
        suffix: "custom",
        isDropdown: true,
        width: width,
        autoFill: false,
        emptyText: "",
        changeCallback: (typeof fnSelectedCallback == "function") ? fnSelectedCallback : null,
        triggerSelectedFirstLoad: true
    });
}
//Adding attribute empty text for custom combobox
function RegisterComboWithEmptyText(selector, width, emptyText, fnSelectedCallback) {
    $(selector).customCombo({
        suffix: "custom",
        isFilter: true,
        isDropdown: false,
        width: width,
        autoFill: false,
        searchContain: true,
        emptyText: emptyText,
        changeCallback: (typeof fnSelectedCallback == "function") ? fnSelectedCallback : null,
        triggerSelectedFirstLoad: false
    });
}

//Adding attribute filter for custom combobox
function RegisterComboFilter(selector, width, fnSelectedCallback) {

    $(selector).customCombo({
        suffix: "custom",
        isFilter: true,
        width: width,
        autoFill: true,
        emptyText: "",
        changeCallback: (typeof fnSelectedCallback == "function") ? fnSelectedCallback : null,
        triggerSelectedFirstLoad: true
    });
}

//Disable-Enable custom combobox
function DisableCombo(selector, isDisabled) {
    if (isDisabled) {
        $.customCombo.deactivate(selector);
        SetBackgroundForCombobox($(selector), 'lightgrey');
    } else {
        $.customCombo.activate(selector);
        SetDefaultBackgroundForCombobox($(selector));
    }
}

//the function is defined to get text of custom combobox
function ComboGetText(selector) {
    return $.customCombo.getText(selector);
}

//the function is defined to get value of custom combobox
function ComboGetValue(selector) {
    return $.customCombo.getValue(selector);
}

//the function is defined to set value of custom combobox
function ComboSetValue(selector, value) {
    return $.customCombo.setValue(selector, value);
}

//the function is defined to set text of custom combobox
function ComboSetText(selector, value) {
    return $.customCombo.setText(selector, value);
}

//the function is defined to refresh custom combobox
function ComboReload(selector, isDefaultBlank) {
    return $.customCombo.changeOptions(selector, isDefaultBlank);
}
//the function is defined to clear data custom combobox
function ComboClearData(selector, isDefaultBlank) {
    $(selector).find('option').remove().end();
    ComboReload(selector, isDefaultBlank);
}
//the function is defined to refresh custom combobox
function ComboReloadByJsonData(selector, result, opts) {

    var keyValue = (typeof opts.KeyValue == 'undefined') ? 'Id' : opts.KeyValue;
    var keyText = (typeof opts.KeyText == 'undefined') ? 'Name' : opts.KeyText;
    var isDefaultBlank = (typeof opts.DefaultBlank == 'undefined') ? false : opts.DefaultBlank;

    $(selector).find('option').remove().end();
    if (result != null) {
        for (var i = 0; i < result.length; i++) {
            var item = result[i];
            $(selector).append($('<option></option>').val(eval('item.' + keyValue)).html(eval('item.' + keyText)));
        }
    }
    ComboReload(selector, isDefaultBlank);
}

/*  
Description : Get text of drowdownlist control
*/
function GetTextDropdownlist(selector) {
    if ($(selector).length == 0)
        return '';
    var indexValue = $(selector)[0].selectedIndex;
    if (indexValue == -1) {
        return '';
    }
    var textValue = $(selector)[0].options[indexValue].innerHTML;
    return textValue;
}


/*  
Control : Accordion & Accordion Expand jQuery
Description: the function is defined to register Accordion control of jquery
*/
function RegisterAccordion(selector, isCollapsible, isActive, fnAccordionOnChange) {
    $(selector).accordion({
        collapsible: isCollapsible,
        autoHeight: true,
        heightStyle: "content",
        active: isActive,
        change: function (event, ui) {
            if (typeof fnAccordionOnChange == "function") {
                fnAccordionOnChange(event, ui);
            }
        }
    });
}

//Firing event only when users expand accordion
function RegisterAccordionOnActivate(selector, isCollapsible, isActive, fnAccordionOnChange) {
    $(selector).accordion({
        collapsible: isCollapsible,
        autoHeight: true,
        heightStyle: "content",
        active: isActive,
        activate: function (event, ui) {
            if (ui.newHeader.text() != "") {
                fnAccordionOnChange(event, ui);
            }
        }
    });
}

/*  
Control : Accordion & Accordion Expand jQuery
Description: the function is defined to register Accordion Custom control
Behavior : These group boxes shall be able to collapse and expand. 
The group box shall show only few fields when it is collapsed and it shall show all fields when it is expanded.
*/
function RegisterAccordionCustom(selector, isCollapsed) {

    //Using css of jquery ui
    $(selector).addClass("ui-accordion ui-widget ui-helper-reset ui-accordion-icons");
    $(selector + " .accordion").addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active");

    if (isCollapsed) {
        $(selector + " h3").attr("class", "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all");
        $(selector + " h3").append('<span class="ui-icon ui-icon-triangle-1-e"></span>');
        $(selector + " .accordion-collapsed").hide();
    } else {
        $(selector + " h3").attr("class", "ui-accordion-header ui-helper-reset ui-state-active ui-corner-top");
        $(selector + " h3").append('<span class="ui-icon ui-icon-triangle-1-s"></span>');
    }

    //Register accordion event for header of section
    $(selector + " h3").click(function () {
        if ($(selector + " .accordion-collapsed").css('display') == 'none') {
            $(selector + " h3").attr("class", "ui-accordion-header ui-helper-reset ui-state-active ui-corner-top");
            $(selector + " h3 span").attr('class', 'ui-icon ui-icon-triangle-1-s');
            $(selector + " .accordion-collapsed").show();
        } else {
            $(selector + " h3").attr("class", "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all");
            $(selector + " h3 span").attr('class', 'ui-icon ui-icon-triangle-1-e');
            $(selector + " .accordion-collapsed").hide();
        }
    });
}
//Expand-Collapsed accordion control
function ExpandAccordion(selector, isExpand) {
    $(selector).accordion("activate", (isExpand == true ? 0 : 1));
}

//Encode string to html code
function EncodeHTML(strSource) {
    if (strSource != null) {
        return strSource.replace(/\&/g, '&amp;').replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/\"/g, '&quot;').replace(/\'/g, " ");
    }
    else
        return strSource;
}
//Decode string to html code
function DecodeHTML(strSource) {

    if (strSource != null) {
        return strSource.replace(/&amp;/gi, '&').replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/&quot;/gi, '"').replace(/&#39;/gi, "'");
    }
    else
        return strSource;
}

function CallFunctionWithAjaxPost(opts, fnSuccessCallback, fnCompleteCallback, fnErrorCallback) {
    $.ajax(
		{
		    type: "POST",
		    url: opts.ActionUrl,
		    data: opts,
		    async: false,
		    cache: false,
		    dataType: "json",
		    success: function (data) {
		        if (typeof fnSuccessCallback == "function") {
		            fnSuccessCallback(data);
		        }
		    },
		    complete: function (data) {
		        if (typeof fnCompleteCallback == "function") {
		            fnCompleteCallback(data);
		        }
		    },
		    error: function (data) {
		        if (typeof fnErrorCallback == "function") {
		            fnErrorCallback(data);
		        }
		    }
		});
}

function CallFunctionWithAjaxPostWithContentType(opts, fnSuccessCallback, fnCompleteCallback, fnErrorCallback) {
    $.ajax(
		{
		    type: "POST",
		    url: opts.ActionUrl,
		    data: JSON.stringify(opts.data),
		    contentType: 'application/json',
		    async: false,
		    cache: false,
		    dataType: "json",
		    success: function (data) {
		        if (typeof fnSuccessCallback == "function") {
		            fnSuccessCallback(data);
		        }
		    },
		    complete: function (data) {
		        if (typeof fnCompleteCallback == "function") {
		            fnCompleteCallback(data);
		        }
		    },
		    error: function (data) {
		        if (typeof fnErrorCallback == "function") {
		            fnErrorCallback(data);
		        }
		    }
		});
}

/* 
Only allow number only on textbox control (selector)
*/
function NumberOnly(selector) {
    if (typeof selector != 'object') {
        if (selector.indexOf('#') == -1) {
            selector = '#' + selector;
        }
        selector = $(selector);
    }

    selector.bind('blur', function (e) {
        var textVal = $(this).val();
        if (textVal.indexOf('.') >= 0 || isNaN($(this).val())) {
            $(this).val('');
        }
        return;
    });

    selector.keypress(function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
        return true;
    });
}

function DecimalOnly(selector) {
    if (typeof selector != 'object') {
        if (selector.indexOf('#') == -1) {
            selector = '#' + selector;
        }
        selector = $(selector);
    }
    selector.keypress(function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57)) {
            return false;
        }
        if (e.which == 46 && selector.val() == "") return false;
        var PosDecimal = selector.val().indexOf('.');
        if (e.which == 46 && PosDecimal >= 0) return false;
        return true;
    });
}
/* 
Only allow decimal number only on textbox control (selector)
*/
function NumberOnlyTextBox(txtName) {
    $('#' + txtName).keypress(function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
        return true;
    });
}

function DecimalTextBox(txtName) {
    $('#' + txtName).bind('blur', function (e) {

        var textVal = $(this).val();

        if (textVal.indexOf('.') == 0 || textVal.lastIndexOf('.') == textVal.length - 1 || isNaN($(this).val())) {
            $(this).val('');
        }
        return;
    });

    $('#' + txtName).keypress(function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57)) {
            return false;
        }

        var txtValue = document.getElementById(txtName);

        if (e.which == 46 && txtValue.value == "") return false;

        var PosDecimal = txtValue.value.indexOf('.');
        if (e.which == 46 && PosDecimal >= 0) return false;

        return true;
    });
}

/* 
description: set background for combobox
*/
function SetBackgroundForCombobox(selector, hexColorCode) {
    selector.next().css('background', hexColorCode);
}
/* 
description: set default background of combobox
*/
function SetDefaultBackgroundForCombobox(selector) {
    selector.next().css('background', '#FFFFFF');
}

/*
description: count items in combobox
*/
$.fn.ItemCount = function () {
    return $('select' + this + ' option').length;
}

//Create popup
function CreateDialog(options) {
    //Checking the dialog is still existed
    var defaults = {
        name: 'dialog',
        bgiframe: true,
        autoOpen: false,
        width: 1000,
        height: 600,
        resizable: false,
        modal: true,
        title: "",
        show: {
            effect: 'slide',
            complete: function () {

            }
        },
        buttons: {
            Close: function () {
                $(this).dialog("close");
                $(setting.name).remove();
            }
        },
        closeOnEscape: true
    };
    var setting = $.extend(defaults, options);

    //Create dialog to show ticket details
    if (setting.name == 'dialog') {
        _dialog = $("<div id=\"" + setting.name + "\"></div>");
        $(document.body).append(_dialog);
    } else {
        _dialog = $(setting.name);
    }
    return _dialog.dialog(setting);
}

// DateTime functions
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

var MONTH_NAMES = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var DAY_NAMES = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
function LZ(x) { return (x < 0 || x > 9 ? "" : "0") + x; }

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val, format) {
    var date = getDateFromFormat(val, format);
    if (date == 0) { return false; }
    return true;
}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1, dateformat1, date2, dateformat2) {
    var d1 = getDateFromFormat(date1, dateformat1);
    var d2 = getDateFromFormat(date2, dateformat2);
    if (d1 == 0 || d2 == 0) {
        return -1;
    }
    else if (d1 > d2) {
        return 1;
    }
    return 0;
}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date, format) {
    format = format + "";
    var result = "";
    var i_format = 0;
    var c = "";
    var token = "";
    var y = date.getYear() + "";
    var M = date.getMonth() + 1;
    var d = date.getDate();
    var E = date.getDay();
    var H = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    var yyyy, yy, MMM, MM, dd, hh, h, mm, ss, ampm, HH, H, KK, K, kk, k;
    // Convert real date parts into formatted versions
    var value = new Object();
    if (y.length < 4) { y = "" + (y - 0 + 1900); }
    value["y"] = "" + y;
    value["yyyy"] = y;
    value["yy"] = y.substring(2, 4);
    value["M"] = M;
    value["MM"] = LZ(M);
    value["MMM"] = MONTH_NAMES[M - 1];
    value["NNN"] = MONTH_NAMES[M + 11];
    value["d"] = d;
    value["dd"] = LZ(d);
    value["E"] = DAY_NAMES[E + 7];
    value["EE"] = DAY_NAMES[E];
    value["H"] = H;
    value["HH"] = LZ(H);
    if (H == 0) { value["h"] = 12; }
    else if (H > 12) { value["h"] = H - 12; }
    else { value["h"] = H; }
    value["hh"] = LZ(value["h"]);
    if (H > 11) { value["K"] = H - 12; } else { value["K"] = H; }
    value["k"] = H + 1;
    value["KK"] = LZ(value["K"]);
    value["kk"] = LZ(value["k"]);
    if (H > 11) { value["a"] = "PM"; }
    else { value["a"] = "AM"; }
    value["m"] = m;
    value["mm"] = LZ(m);
    value["s"] = s;
    value["ss"] = LZ(s);
    while (i_format < format.length) {
        c = format.charAt(i_format);
        token = "";
        while ((format.charAt(i_format) == c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
        }
        if (value[token] != null) { result = result + value[token]; }
        else { result = result + token; }
    }
    return result;
}

// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
    var digits = "1234567890";
    for (var i = 0; i < val.length; i++) {
        if (digits.indexOf(val.charAt(i)) == -1) { return false; }
    }
    return true;
}

function _getInt(str, i, minlength, maxlength) {
    for (var x = maxlength; x >= minlength; x--) {
        var token = str.substring(i, i + x);
        if (token.length < minlength) { return null; }
        if (_isInteger(token)) { return token; }
    }
    return null;
}

// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val, format) {
    val = val + "";
    format = format + "";
    var i_val = 0;
    var i_format = 0;
    var c = "";
    var token = "";
    var token2 = "";
    var x, y;
    var now = new Date();
    var year = now.getYear();
    var month = now.getMonth() + 1;
    var date = 1;
    var hh = now.getHours();
    var mm = now.getMinutes();
    var ss = now.getSeconds();
    var ampm = "";

    while (i_format < format.length) {
        // Get next token from format string
        c = format.charAt(i_format);
        token = "";
        while ((format.charAt(i_format) == c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
        }
        // Extract contents of value based on format token
        if (token == "yyyy" || token == "yy" || token == "y") {
            if (token == "yyyy") { x = 4; y = 4; }
            if (token == "yy") { x = 2; y = 2; }
            if (token == "y") { x = 2; y = 4; }
            year = _getInt(val, i_val, x, y);
            if (year == null) { return 0; }
            i_val += year.length;
            if (year.length == 2) {
                if (year > 70) { year = 1900 + (year - 0); }
                else { year = 2000 + (year - 0); }
            }
        }
        else if (token == "MMM" || token == "NNN") {
            month = 0;
            for (var i = 0; i < MONTH_NAMES.length; i++) {
                var month_name = MONTH_NAMES[i];
                if (val.substring(i_val, i_val + month_name.length).toLowerCase() == month_name.toLowerCase()) {
                    if (token == "MMM" || (token == "NNN" && i > 11)) {
                        month = i + 1;
                        if (month > 12) { month -= 12; }
                        i_val += month_name.length;
                        break;
                    }
                }
            }
            if ((month < 1) || (month > 12)) { return 0; }
        }
        else if (token == "EE" || token == "E") {
            for (var i = 0; i < DAY_NAMES.length; i++) {
                var day_name = DAY_NAMES[i];
                if (val.substring(i_val, i_val + day_name.length).toLowerCase() == day_name.toLowerCase()) {
                    i_val += day_name.length;
                    break;
                }
            }
        }
        else if (token == "MM" || token == "M") {
            month = _getInt(val, i_val, token.length, 2);
            if (month == null || (month < 1) || (month > 12)) { return 0; }
            i_val += month.length;
        }
        else if (token == "dd" || token == "d") {
            date = _getInt(val, i_val, token.length, 2);
            if (date == null || (date < 1) || (date > 31)) { return 0; }
            i_val += date.length;
        }
        else if (token == "hh" || token == "h") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 1) || (hh > 12)) { return 0; }
            i_val += hh.length;
        }
        else if (token == "HH" || token == "H") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 0) || (hh > 23)) { return 0; }
            i_val += hh.length;
        }
        else if (token == "KK" || token == "K") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 0) || (hh > 11)) { return 0; }
            i_val += hh.length;
        }
        else if (token == "kk" || token == "k") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 1) || (hh > 24)) { return 0; }
            i_val += hh.length; hh--;
        }
        else if (token == "mm" || token == "m") {
            mm = _getInt(val, i_val, token.length, 2);
            if (mm == null || (mm < 0) || (mm > 59)) { return 0; }
            i_val += mm.length;
        }
        else if (token == "ss" || token == "s") {
            ss = _getInt(val, i_val, token.length, 2);
            if (ss == null || (ss < 0) || (ss > 59)) { return 0; }
            i_val += ss.length;
        }
        else if (token == "TT") {
            if (val.substring(i_val, i_val + 2).toLowerCase() == "am") { ampm = "AM"; }
            else if (val.substring(i_val, i_val + 2).toLowerCase() == "pm") { ampm = "PM"; }
            else { return 0; }
            i_val += 2;
        }
        else {
            if (val.substring(i_val, i_val + token.length) != token) { return 0; }
            else { i_val += token.length; }
        }
    }
    // If there are any trailing characters left in the value, it doesn't match
    if (i_val != val.length) { return 0; }
    // Is date valid for month?
    if (month == 2) {
        // Check for leap year
        if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { // leap year
            if (date > 29) { return 0; }
        }
        else { if (date > 28) { return 0; } }
    }
    if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
        if (date > 30) { return 0; }
    }
    // Correct hours value
    if (hh < 12 && ampm == "PM") { hh = hh - 0 + 12; }
    else if (hh > 11 && ampm == "AM") { hh -= 12; }
    var newdate = new Date(year, month - 1, date, hh, mm, ss);
    return newdate.getTime();
}

// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d   MMM d, y   MMM d,y   y-MMM-d   d-MMM-y  MMM d
// M/d/y   M-d-y      M.d.y     MMM-d     M/d      M-d
// d/M/y   d-M-y      d.M.y     d-MMM     d/M      d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------
function parseDate(val) {
    var preferEuro = (arguments.length == 2) ? arguments[1] : false;
    generalFormats = new Array('y-M-d', 'MMM d, y', 'MMM d,y', 'y-MMM-d', 'd-MMM-y', 'MMM d');
    monthFirst = new Array('M/d/y', 'M-d-y', 'M.d.y', 'MMM-d', 'M/d', 'M-d');
    dateFirst = new Array('d/M/y', 'd-M-y', 'd.M.y', 'd-MMM', 'd/M', 'd-M', 'dd-MMM-yyyy', 'dd-MMM-yyyy h:mm TT');
    var checkList = new Array('generalFormats', preferEuro ? 'dateFirst' : 'monthFirst', preferEuro ? 'monthFirst' : 'dateFirst');
    var d = null;
    for (var i = 0; i < checkList.length; i++) {
        var l = window[checkList[i]];
        for (var j = 0; j < l.length; j++) {
            d = getDateFromFormat(val, l[j]);
            if (d != 0) { return new Date(d); }
        }
    }
    return null;
}

function ValidateMaxLengthOnText(AreaField, maxChars) {

    $('#' + AreaField).bind('blur', function (e) {
        var textVal = $(this).val();

        if (textVal.length > maxChars) {
            OpenAlertPopup("Alert", 'The field Description must be a string with a maximum length of ' + maxChars);
            $(this).val('');
        }
        return;
    });
}

//Process Number Only For List Element by Class
function NumberOnlyForList(selector) {
    if (typeof selector != 'object') {
        if (selector.indexOf('.') == -1) {
            selector = '.' + selector;
        }
        selector = $(selector);
    }

    selector.bind('blur', function (e) {
        var textVal = $(this).val();
        if (textVal.indexOf('.') >= 0 || isNaN($(this).val())) {
            $(this).val('');
        }
        return;
    });

    selector.keypress(function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
        return true;
    });
}

function EnableRequired(control) {
    /*if ($(control).hasClass("labelInput")) {
    $(control).removeClass("labelInput");
    }*/
    try {
        $(control).addClass("labelRequired");
    } catch (e) {
        //Skip some error
    }
}

function DisableRequired(control) {
    try {
        if ($(control).hasClass("labelRequired")) {
            $(control).removeClass("labelRequired");
        }
        $(control).addClass("labelInput");
    } catch (e) {
        //Skip some error
    }
}

//Example : ".requiredControl"
function EnableRequiredClass(className) {
    try {
        $(className).addClass("labelRequired");
    } catch (e) {
        //Skip some error
    }
}

function DisableRequiredClass(className) {
    try {
        $(className).removeClass("labelRequired");
    } catch (e) {
        //Skip some error
    }
}

///USING    :  $("#FormID").resetValidation()   //Summary Error
///USING    :  $("#FormID").formReset()         //Form Data
(function ($) {
    //re-set all client validation given a jQuery selected form or child
    $.fn.resetValidation = function () {

        var $form = this.closest('form');

        //reset jQuery Validate's internals
        //$form.validate().resetForm();

        //reset unobtrusive validation summary, if it exists
        $form.find("[data-valmsg-summary=true]")
			.removeClass("validation-summary-errors")
			.addClass("validation-summary-valid")
			.find("ul").empty();

        //reset unobtrusive field level, if it exists
        $form.find("[data-valmsg-replace]")
			.removeClass("field-validation-error")
			.addClass("field-validation-valid")
			.empty();

        return $form;
    };

    //reset a form given a jQuery selected form or a child
    //by default validation is also reset
    $.fn.formReset = function (resetValidation) {
        var $form = this.closest('form');

        $form[0].reset();

        if (resetValidation == undefined || resetValidation) {
            $form.resetValidation();
        }

        return $form;
    };
})(jQuery);

function IsNullOrWhiteSpace(value) {
    var result = false;
    if (typeof value == "undefined" || value == null || $.trim(value) == "") {
        result = true;
    }
    return result;
}

function IsNullOrUndefined(value) {
    var result = false;
    if (typeof value == "undefined" || value == null) {
        result = true;
    }
    return result;
}

//Add "-" to string dateTime
function AppendSlashToDataTime(input) {

    if (input != null && input != "") {
        var day = input.substring(0, 2);
        var month = input.substring(2, 5);
        var year = input.substring(5, 9);

        return day + "-" + month + "-" + year;
    }
    return null;
}
